package com.creatingrevolutions.vbukit.lib;

import android.util.Log;

import com.creatingrevolutions.vbukit.lib.handler.BaseVbukitHandler;

public class ScreenSaver
{	
	BaseVbukitHandler handler;
	boolean isRunning = false;
	volatile long before;
	int dueTimeInSecs = (60 * 2); // 2 minutes as default timeout
	
	public ScreenSaver(int dueTimeInSecs, BaseVbukitHandler handler)
	{
		this.handler = handler;
		this.dueTimeInSecs = dueTimeInSecs;
	}
	
	public ScreenSaver(BaseVbukitHandler handler)
	{
		this.handler = handler;
	}
	
	public void start() 
	{
		isRunning = true;
		
		Thread t = new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				before = System.currentTimeMillis();
				
				while( isRunning )
				{
					long now = System.currentTimeMillis();
					long diff = now - before;
					
					try {
						Thread.sleep(1000);
					} catch ( Exception e ) {}
					
					// Difference in seconds
					long diffSec = diff / 1000;
					Log.e("", "Screen Saver - Difference in seconds " + diffSec);
					
					// Difference in minutes
					long diffMin = diff / (60 * 1000);
					Log.e("", "Screen Saver - Difference in minutes " + diffMin);
					
					if ( diffSec >= dueTimeInSecs ) 
					{
						if ( handler != null ) {
							handler.updateInfo(true, null, null);
						}
						before = System.currentTimeMillis();
					}
				}
			}
		});
		t.start();
	}
	
	public void stop()
	{
		this.isRunning = false;
	}
	
	public boolean isRunning() {
		return this.isRunning;
	}
	
	public void setStartTime(long millisecs) {
		this.before = millisecs;
	}
}
